<?php 

class StringUtil {
	
	/**
	 * Returns the first non-empty string or null if all are empty(null or zero-length).
	 * @return string
	 */
	public static function firstNonEmptyString() {
		$argsCount = func_num_args();
		$argsList = func_get_args();
		for($i = 0; $i < $argsCount; $i++) {
			if(strlen($argsList[$i]) > 0) {
				return $argsList[$i];
			}
		}
		return null;
	}
	
	/**
	 * Parses the i18n string into an array with langs as keys and texts as values
	 * @param $s  e.g. {fr=Text in french}{zh-tw=text in zh-tw}
	 * @return array
	 */
	public static function parseI18n($s) {
		$length = mb_strlen($s);
		if($s == null || $length == 0) {
			return null;
		} 
		$cursor = 0;
		$i18narray = array();
		while($cursor < $length) {
			$open = mb_strpos($s, "{", $cursor);
			if($open === false) { // not found.
				break;
			}
			$close = mb_strpos($s, "}", $cursor);
			if($close === false) {
				throw new Exception("Invalid i18n format: " . $s . " (valid format example: {fr=Text in french}{zh-tw=text in zh-tw} )");
			}
			$content = mb_split("=", mb_substr($s, $open + 1, $close - $open - 1), 2);
			$i18narray[$content[0]] = $content[1];
			$cursor = $close + 1;
		}
		return $i18narray;
	}
	
//	public static function parseI18n($s) {
//		$length = mb_strlen($s);
//		if($s == null || $length == 0) {
//			return null;
//		} 
//		$cursor = 0;
//		$i18narray = array();
//		while($cursor < $length) {
//			$open = mb_strpos($s, "{", $cursor);
//			if($open === false) { // not found.
//				break;
//			}
//			$close = mb_strpos($s, "}", $cursor);
//			if($close === false) {
//				throw new Exception("Invalid i18n format: " . $s . " (valid format example: {fr=Text in french}{zh-tw=text in zh-tw} )");
//			}
//			$content = mb_split("=", mb_substr($s, $open + 1, $close - $open - 1), 2);
//			$i18narray[$content[0]] = $content[1];
//			$cursor = $close + 1;
//		}
//		return $i18narray;
//	}	
}

?>